package com.xingzhi.shortvideosharingplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingzhi.shortvideosharingplatform.common.Result;
import com.xingzhi.shortvideosharingplatform.model.SystemNotification;
import com.xingzhi.shortvideosharingplatform.service.SystemNotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/notifications")
public class SystemNotificationController {

    @Autowired
    private SystemNotificationService notificationService;
    
    /**
     * 获取用户通知列表（分页）
     */
    @GetMapping("/list")
    public Result<Page<SystemNotification>> getNotifications(
            @RequestParam Long userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            // TODO: 从Token中获取用户ID
            Page<SystemNotification> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<SystemNotification> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SystemNotification::getUserId, userId)
                      .orderByDesc(SystemNotification::getCreatedTime);
            
            Page<SystemNotification> resultPage = notificationService.page(pageInfo, queryWrapper);
            return Result.success(resultPage);
        } catch (Exception e) {
            log.error("获取通知列表失败", e);
            return Result.error(500, "获取通知列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记通知为已读
     */
    @PutMapping("/read/{notificationId}")
    public Result<Boolean> markAsRead(@PathVariable Long notificationId, @RequestParam Long userId) {
        try {
            // TODO: 从Token中获取用户ID
            boolean success = notificationService.markAsRead(notificationId, userId);
            if (success) {
                return Result.success(true, "标记已读成功");
            } else {
                return Result.error(400, "标记已读失败，可能通知不存在或无权限操作");
            }
        } catch (Exception e) {
            log.error("标记通知已读失败", e);
            return Result.error(500, "标记通知已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadCount(@RequestParam Long userId) {
        try {
            // TODO: 从Token中获取用户ID
            int count = notificationService.getUnreadCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读通知数量失败", e);
            return Result.error(500, "获取未读通知数量失败: " + e.getMessage());
        }
    }
} 